package com.zhuojy.equity.mall.admin.web.security.component;

import com.zhuojy.equity.mall.admin.common.constant.JwtConstants;
import com.zhuojy.equity.mall.admin.manager.token.TokenManager;
import com.zhuojy.equity.mall.admin.service.AdminUserDetailsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	private final AdminUserDetailsService adminUserDetailsService;

	private final TokenManager tokenManager;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		String authHeader = request.getHeader(JwtConstants.TOKEN_HEADER);
		if (authHeader != null && authHeader.startsWith(JwtConstants.TOKEN_HEAD)) {
			String authToken = authHeader.substring(JwtConstants.TOKEN_HEAD.length());// The part after "Bearer "
			String username = tokenManager.getUserNameFromToken(authToken);
			log.info("checking username:{}", username);
			if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
				UserDetails userDetails = adminUserDetailsService.loadUserByUsername(username);
				if (tokenManager.validateToken(authToken, userDetails)) {
					UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
							userDetails, null, userDetails.getAuthorities());
					authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
					log.info("authenticated user:{}", username);
					SecurityContextHolder.getContext().setAuthentication(authentication);
				}
			}
		}
		chain.doFilter(request, response);
	}
}
